package com.tl.satoken.controller;

import com.tl.satoken.common.Result;
import com.tl.satoken.domain.entity.MBTISquare;
import com.tl.satoken.domain.entity.Player;
import com.tl.satoken.netty.ChannelGroupManager;
import com.tl.satoken.netty.WebSocketFrameHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/game")
public class GameController {
    private static final Logger log = LoggerFactory.getLogger(GameController.class);
    
    @Autowired
    private ChannelGroupManager channelGroupManager;

    @PostMapping("/join")
    public Result<Map<String, Object>> joinGame(@RequestBody Player player) {
        log.info("玩家 {} 通过HTTP请求加入游戏", player.getUsername());
        player.setId(player.getUsername());
        
        // 生成临时房间ID，实际房间分配在WebSocket连接时进行
        String tempRoomId = player.getMbtiType().name() + "_Room_Temp_" + System.currentTimeMillis();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("message", "请通过WebSocket连接加入房间");
        response.put("playerId", player.getId());
        response.put("roomId", tempRoomId);
        
        return Result.success(response);
    }

    @GetMapping("/rooms")
    public Result<Map<String, Object>> getAllRooms() {
        try {
            Map<String, Object> response = new HashMap<>();
            response.put("totalRooms", channelGroupManager.getTotalRooms());
            response.put("totalPlayers", channelGroupManager.getTotalPlayers());
            response.put("onlineCount", WebSocketFrameHandler.getOnlineCount());
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取房间信息时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "获取房间信息失败: " + e.getMessage()));
        }
    }

    @GetMapping("/connections")
    public Result<Map<String, Object>> getConnections() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("totalRooms", channelGroupManager.getTotalRooms());
        stats.put("totalPlayers", channelGroupManager.getTotalPlayers());
        stats.put("onlineCount", WebSocketFrameHandler.getOnlineCount());
        return Result.success(stats);
    }

    @GetMapping("/room/{roomId}")
    public Result<Map<String, Object>> getRoomInfo(@PathVariable String roomId) {
        try {
            // 从ChannelGroupManager获取房间信息
            int playerCount = channelGroupManager.getRoomPlayerCount(roomId);
            
            Map<String, Object> roomInfo = new HashMap<>();
            roomInfo.put("roomId", roomId);
            roomInfo.put("currentPlayers", playerCount);
            roomInfo.put("maxPlayers", 1000);
            
            // 获取房间内的玩家列表（这里需要从WebSocketFrameHandler获取）
            List<Player> players = getPlayersInRoom(roomId);
            
            Map<String, Object> response = new HashMap<>();
            response.put("roomInfo", roomInfo);
            response.put("players", players);
            
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取房间信息时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "房间不存在或获取失败"));
        }
    }
    
    private List<Player> getPlayersInRoom(String roomId) {
        return WebSocketFrameHandler.getPlayersInRoom(roomId);
    }

    @GetMapping("/mbti/types")
    public Result<Map<String, Object>> getMBTITypes() {
        try {
            Map<String, Map<String, Object>> types = new HashMap<>();

            for (MBTISquare mbti : MBTISquare.values()) {
                Map<String, Object> typeInfo = Map.of(
                    "type", mbti.name(), 
                    "displayName", mbti.getDisplayName(), 
                    "description", mbti.getDescription()
                );
                types.put(mbti.name(), typeInfo);
            }

            Map<String, Object> response = Map.of(
                "types", types, 
                "totalCount", MBTISquare.values().length
            );
            return Result.success(response);
        } catch (Exception e) {
            log.error("获取MBTI类型列表时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "获取类型列表失败: " + e.getMessage()));
        }
    }
    
    @GetMapping("/debug/sessions")
    public Result<Map<String, Object>> getSessionDebugInfo() {
        try {
            Map<String, Object> debugInfo = new HashMap<>();
            debugInfo.put("onlineCount", WebSocketFrameHandler.getOnlineCount());
            debugInfo.put("totalRooms", channelGroupManager.getTotalRooms());
            debugInfo.put("totalPlayers", channelGroupManager.getTotalPlayers());
            
            return Result.success(debugInfo);
        } catch (Exception e) {
            log.error("获取调试信息时出现异常: {}", e.getMessage(), e);
            return Result.success(Map.of("message", "获取调试信息失败: " + e.getMessage()));
        }
    }
}


